package net.mikoo.seals.boss.web.controller;


import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import net.mikoo.seals.boss.biz.services.CompanyServices;
import net.mikoo.seals.boss.biz.services.DevicesModelServices;
import net.mikoo.seals.boss.biz.services.DevicesServices;
import net.mikoo.seals.boss.common.BaseController;
import net.mikoo.seals.boss.common.PageModel;
import net.mikoo.seals.boss.common.WebContext;
import net.mikoo.seals.boss.common.enums.DevicesStatusEnum;
import net.mikoo.seals.boss.common.exception.ParametersException;
import net.mikoo.seals.boss.common.utils.CSVUtil;
import net.mikoo.seals.boss.common.utils.DateUtil;
import net.mikoo.seals.boss.common.utils.FileUtil;
import net.mikoo.seals.boss.model.Collections;
import net.mikoo.seals.boss.model.Company;
import net.mikoo.seals.boss.model.CompanyQuery;
import net.mikoo.seals.boss.model.Devices;
import net.mikoo.seals.boss.model.DevicesModel;
import net.mikoo.seals.boss.model.DevicesQuery;
import net.mikoo.seals.boss.model.DevicesRenew;



@Controller
@RequestMapping("/admin/devices")
public class DevicesController extends BaseController {
	
	Logger logger = LoggerFactory.getLogger(DevicesController.class);
	
	@Autowired
	private ServletContext servletContext;
	
	@Autowired
	private DevicesServices devicesServices;
	
	@Autowired
	private DevicesModelServices devicesModelServices;
	
	@Autowired
	private CompanyServices companyServices;
	
	
	@RequestMapping("/initList")
	public String initList(DevicesQuery query, HttpServletRequest request, Model model) {
		query.setDevicesStatus(DevicesStatusEnum.INIT.code());
		PageModel<Devices> pm  = devicesServices.getPageByQuery(query);
		model.addAttribute("pm", pm);
		model.addAttribute("query", query);
		return resultView(ADMIN_VIEW, "devices/initList");
	}
	
	@RequestMapping("/effeList")
	public String effeList(DevicesQuery query, HttpServletRequest request, Model model) {
		
		//effective
		query.setDevicesStatus("EFFECTIVE");
		
		PageModel<Devices> pm  = devicesServices.getPageByQuery(query);
		model.addAttribute("pm", pm);
		model.addAttribute("query", query);
		return resultView(ADMIN_VIEW, "devices/effeList");
	}
	
	
	@RequestMapping("/deadList")
	public String deadList(DevicesQuery query, HttpServletRequest request, Model model) {
		
		query.setDevicesStatus(DevicesStatusEnum.DESERTED.code());
		PageModel<Devices> pm  = devicesServices.getPageByQuery(query);
		model.addAttribute("pm", pm);
		model.addAttribute("query", query);
		return resultView(ADMIN_VIEW, "devices/deadList");
	}
	

	@RequestMapping("/form")
	public String form(Model model) {
		
		CompanyQuery query  = new CompanyQuery();
		
		List<Company> companys =  companyServices.getListByQuery(query);
		model.addAttribute("companys", companys);
		
		
		List<DevicesModel> models =  devicesModelServices.getList();
		model.addAttribute("models", models);
		
		return resultView(ADMIN_VIEW, "devices/form");
	}
	
	@RequestMapping("/info")
	public String info(Long devicesId,Model model) {
		
		Devices devices = devicesServices.getInfoById(devicesId);
		model.addAttribute("devices", devices);
		return resultView(ADMIN_VIEW, "devices/info");
	}
	
	@RequestMapping("/renew")
	public String renew(Long devicesId,Model model) {
		
		Devices devices = devicesServices.getInfoById(devicesId);
		model.addAttribute("devices", devices);
		return resultView(ADMIN_VIEW, "devices/renew");
	}
	
	@RequestMapping("/renew/post")
	@ResponseBody
	public Map<String,Object> renewPost(DevicesRenew renew,Model model,HttpServletRequest request) {
		
		try {

			Long partyId = getCurrentPartyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			renew.setOperatorId(partyId);
			devicesServices.renew(renew);
			return result(SUCCESS, "添加成功");
		} catch (ParametersException e) {
			logger.error("", e);
			return result(ERROR, e.getMessage());
		} catch (Exception e) {
			logger.error("", e);
			return result(ERROR, "系统出错");
		}
	}
	
	
	@RequestMapping("/create")
	@ResponseBody
	public Map<String,Object> create(Devices devices,HttpServletRequest request, Model model) {
		try {
			
			
			devicesServices.save(devices);
			return result(SUCCESS, "添加成功");
		}catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			logger.error("",e);
			return result(ERROR, "系统出错");
		}
	}

	@RequestMapping("/edit")
	public String edit(Long devicesId, Model model) {
		Devices devices = devicesServices.getInfoById(devicesId);
		model.addAttribute("devices", devices);
		return resultView(ADMIN_VIEW, "devices/edit");
	}
	
	
	@RequestMapping("/modify")
	public Map<String,Object> modify(Devices devices, Model model) {
		
		try {
			devicesServices.modify(devices);
			return result(SUCCESS, "添加成功");
		}catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			logger.error("",e);
			return result(ERROR, "系统出错");
		}
	}
	
	
	@RequestMapping("/delete")
	@ResponseBody
	public Map<String,Object> delete(Devices devices,HttpServletRequest request, Model model) {
		try {
			
			devicesServices.deleteById(devices);
			return result(SUCCESS, "添加成功");
		}catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			logger.error("",e);
			return result(ERROR, "系统出错");
		}
	}
	
	/**
	 * 分配给公司
	 * @param devicesIds
	 * @param compantId
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/alloacation")
	@ResponseBody
	public Map<String,Object> alloacation(Collections colle,HttpServletRequest request, Model model) {
		try {
		
			devicesServices.alloacation(colle.getCompanyId(),colle.getIds());
			return result(SUCCESS, "添加成功");
		}catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			logger.error("",e);
			return result(ERROR, "系统出错");
		}
	}
	
	
	
	@RequestMapping("/imports")
	@ResponseBody
	public Map<String,Object> imports(@RequestParam(value = "file", required = false) MultipartFile file,HttpServletRequest request, Model model) {
		try {
			
			List<Devices> datas =  cvsImprot(file.getInputStream());
			
			int success = 0;
			int error = 0;
			
			for (Devices devices : datas) {
				
				try {
					devicesServices.save(devices);
					success += 1;
				}catch (Exception e) {
					logger.error("",e);
					error += 1;
				}
				
			}
			String msg = "成功导入"+success+"条,失败"+error+"条";
			
			return result(SUCCESS, msg);
		}catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		}catch (IOException e) {
			logger.error("",e);
			return result(ERROR, "文件格式输入有误，解析出错");
		}catch (Exception e) {
			logger.error("",e);
			return result(ERROR, "系统出错");
		}
	}
	
	/**
	 * 印章作废
	 * @param devices
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/deserted")
	@ResponseBody
	public Map<String,Object> deserted(Devices devices,HttpServletRequest request, Model model) {
		try {
			
			
			devicesServices.deserted(devices);
			return result(SUCCESS, "添加成功");
		}catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			logger.error("",e);
			return result(ERROR, "系统出错");
		}
	}
	
	
	@RequestMapping("/changeActivateState")
	@ResponseBody
	public Map<String,Object> changeActivateState(Devices devices,HttpServletRequest request, Model model) {
		try {
			
			devicesServices.changeActivateState(devices);
			return result(SUCCESS, "添加成功");
		}catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			logger.error("",e);
			return result(ERROR, "系统出错");
		}
	}
	
	
	private  List<Devices> cvsImprot(InputStream in) throws Exception {
		
		List<Devices> list = new ArrayList<>();
		try {
			
			List<String> strs = CSVUtil.importCsv(in);
			for (int i = 0; i < strs.size(); i++) {
				if(i < 2) {
					continue;
				}
				String str = strs.get(i);
				String obj[] = str.split(",");
				
				
				String mac = obj[1];
				Date produceDate = DateUtil.stringToDate(obj[2], "yyyy-MM-dd HH:mm:ss") ;
				String devicesCode = obj[3];
				String sign = obj[4];
				String devicesVerson = obj[5];
				String network = obj[6];
				String model = obj[7];
				
				Devices  devices = new Devices();
				devices.setDevicesCode(devicesCode);
				devices.setModel(model);
				devices.setMac(mac);
				devices.setSign(sign);
				devices.setDevicesVerson(devicesVerson);
				devices.setProduceDate(produceDate);
				devices.setNetwork(network);
				list.add(devices);
				
			}
		}catch (Exception e) {
			logger.error("",e);
			throw new ParametersException("格式有误");
		}
		
		
		
		return list;
		
	}
	private  List<Devices> execuImprot(InputStream in) throws Exception {
		
		List<Devices> list = new ArrayList<>();
		Workbook wb0 = null;
		try {
			wb0= new HSSFWorkbook(in);
			Sheet sht0 = wb0.getSheetAt(0);
			
			
			for (Row r : sht0) {
				if (r.getRowNum() < 1) {
					continue;
				}
				
				
				Cell cell0 = r.getCell(0);
				if(cell0== null) {
					break;
				}
				cell0.setCellType(CellType.STRING);
				String devicesCode = cell0.getStringCellValue();
				
				
				Cell cell1 = r.getCell(1);
				cell1.setCellType(CellType.STRING);
				String model = cell1.getStringCellValue();
				
				
				Cell cell2 = r.getCell(2);
				cell2.setCellType(CellType.STRING);
				String devicesVerson = cell2.getStringCellValue();
				
				Cell cell3 = r.getCell(3);
				Date produceDate = cell3.getDateCellValue();
				
				
				Cell cell4 = r.getCell(4);
				cell4.setCellType(CellType.STRING);
				String network = cell4.getStringCellValue();
				
				
				Devices  devices = new Devices();
				devices.setDevicesCode(devicesCode);
				devices.setModel(model);
				devices.setDevicesVerson(devicesVerson);
				devices.setProduceDate(produceDate);
				devices.setNetwork(network);
				list.add(devices);
				
			}
			
		} catch (Exception e) {
			logger.error("",e);
			throw e;
		}finally {
			try {
				wb0.close();
			} catch (IOException e) {
				logger.error("",e);
			}
		}
		
		return list;
		
	}
	
	/**
	 * 选择公司
	 * @param model
	 * @return
	 */
	@RequestMapping("/select")
	public String select(Model model) {
		
		
		return resultView(ADMIN_VIEW, "devices/select");
	}
	
	
	
	@RequestMapping("/downtemp")
	public void downtemp(HttpServletRequest request,HttpServletResponse response) throws IOException{  
		
		InputStream  in = servletContext.getResourceAsStream("/temp/devicesTemp.xls");
		
		byte[] data = FileUtil.toByteArray(in);
		
	    response.reset();  
	    response.setHeader("Content-Disposition", "attachment; filename=devicesTemp.xls");  
	    response.addHeader("Content-Length", "" + data.length);  
	    response.setContentType("application/octet-stream;charset=UTF-8");  
	    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
	    outputStream.write(data);  
	    outputStream.flush();  
	    outputStream.close();  
	}  
	

}
